package org.asiainfo.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.convert.Convert;
import org.asiainfo.common.core.constant.UserConstants;
import org.asiainfo.common.core.utils.StringUtils;
import org.asiainfo.common.idempotent.annotation.RepeatSubmit;
import org.asiainfo.common.log.annotation.Log;
import org.asiainfo.common.log.enums.BusinessType;
import org.springframework.validation.annotation.Validated;
import org.asiainfo.system.service.SysDeptService;
import org.asiainfo.system.domain.vo.SysDeptVo;
import org.asiainfo.system.domain.bo.SysDeptBo;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.asiainfo.common.core.domain.R;
import org.asiainfo.common.web.core.BaseController;
import jakarta.validation.constraints.*;
import org.asiainfo.common.core.validate.AddGroup;
import org.asiainfo.common.core.validate.EditGroup;

import java.util.List;

/**
 * 部门信息表
 *
 * @author dotor-ww
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/dept")
public class SysDeptController extends BaseController {

    private final SysDeptService sysDeptService;

    /**
     * 分页查询
     *
     * @param sysDeptBo 筛选条件
     * @return 查询结果
     */
    @SaCheckPermission("system:dept:list")
    @GetMapping("/list")
    public R<List<SysDeptVo>> list(SysDeptBo sysDeptBo) {
        List<SysDeptVo> sysDeptVos = sysDeptService.queryList(sysDeptBo);
        return R.ok(sysDeptVos);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param deptId 主键
     * @return 单条数据
     */
    @SaCheckPermission("system:dept:query")
    @GetMapping("/{deptId}")
    public R<SysDeptVo> getInfo(@NotNull(message = "部门ID不能为空") @PathVariable("deptId") Long deptId) {
        sysDeptService.checkDeptDataScope(deptId);
        return R.ok(sysDeptService.queryById(deptId));
    }

    /**
     * 新增数据
     *
     * @param sysDeptBo 实体
     * @return 新增结果
     */
    @SaCheckPermission("system:dept:add")
    @Log(title = "部门信息", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SysDeptBo sysDeptBo) {
        if (sysDeptService.checkDeptNameUnique(sysDeptBo)) {
            return R.fail("新增部门'" + sysDeptBo.getDeptName() + "'失败，部门名称已存在");
        }
        return toAjax(sysDeptService.insertByBo(sysDeptBo));
    }

    /**
     * 编辑数据
     *
     * @param sysDeptBo 实体
     * @return 编辑结果
     */
    @SaCheckPermission("system:dept:edit")
    @Log(title = "部门信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysDeptBo sysDeptBo) {
        sysDeptService.checkDeptDataScope(sysDeptBo.getDeptId());
        if (sysDeptService.checkDeptNameUnique(sysDeptBo)) {
            return R.fail("修改部门'" + sysDeptBo.getDeptName() + "'失败，部门名称已存在");
        } else if (sysDeptBo.getParentId().equals(sysDeptBo.getDeptId())) {
            return R.fail("修改部门'" + sysDeptBo.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, sysDeptBo.getDeptStatus())) {
            if (sysDeptService.selectNormalChildrenByDeptId(sysDeptBo.getDeptId()) > 0) {
                return R.fail("部门包含未停用的子部门");
            } else if (sysDeptService.checkDeptExistUser(sysDeptBo.getDeptId())) {
                return R.fail("部门下存在已分配用户,不能停用");
            }
        }
        return toAjax(sysDeptService.updateByBo(sysDeptBo));
    }

    /**
     * 删除数据
     *
     * @param deptId 主键
     * @return 删除是否成功
     */
    @SaCheckPermission("system:dept:remove")
    @Log(title = "部门信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public R<Void> remove(@NotNull(message = "部门ID不能为空") @PathVariable Long deptId) {
        if (sysDeptService.checkDeptExistUser(deptId)) {
            return R.fail("部门下存在已分配用户,不能删除");
        }
        if (sysDeptService.hasChildByDeptId(deptId)) {
            return R.fail("部门下存在子部门,不能删除");
        }
        sysDeptService.checkDeptDataScope(deptId);
        return toAjax(sysDeptService.deleteWithValidById(deptId));
    }

    /**
     * 查询部门下拉树结构
     *
     * @param sysDeptBo 实体
     * @return 查询结果
     */
    @SaCheckPermission("system:dept:query")
    @GetMapping("/optionSelect")
    public R<Object> selectDeptTree(@RequestParam(required = false) Long[] deptIds) {
        return R.ok(sysDeptService.selectDeptByIds(deptIds == null ? null : List.of(deptIds)));
    }

    /**
     * 查询部门列表(排除节点)
     *
     * @param deptId 部门ID
     * @return 查询结果
     */
    @SaCheckPermission("system:dept:list")
    @GetMapping("/list/exclude/{deptId}")
    public R<Object> excludeChild(@NotNull(message = "部门ID不能为空") @PathVariable Long deptId) {
        List<SysDeptVo> sysDeptVos = sysDeptService.queryList(new SysDeptBo());
        sysDeptVos.removeIf(sysDeptVo -> sysDeptVo.getDeptId().equals(deptId) ||
            StringUtils.splitList(sysDeptVo.getAncestors()).contains(Convert.toStr(deptId)));
        return R.ok(sysDeptVos);
    }
}

